package com.hmall.item.web;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MQConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired(required = false)
    private ItemService itemService;

    @Autowired(required = false)
    RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> page(Integer page, Integer size) {
        return itemService.Page(page, size);
    }

    /**
     * 商品id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item findId(@PathVariable Long id) {
        return itemService.findById(id);
    }

    /**
     * 添加商品
     */
    @PostMapping
    public void add(@RequestBody Item item) {

        itemService.add(item);

        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE,MQConstants.ITEM_INSERT_KEY,item.getId());

    }

    /**
     * 下架商品
     */
    @PutMapping("status/{id}/2")
    public void status(@PathVariable Long id){
        itemService.status(id);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE,MQConstants.ITEM_INSERT_KEY,id);
    }


    /**
     * 上架商品
     * @param id
     */
    @PutMapping("status/{id}/1")
    public void status1(@PathVariable Long id){
        itemService.status1(id);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE,MQConstants.ITEM_INSERT_KEY,id);
    }


    /**
     * 修改商品
     * @param item
     */
    @PutMapping
    public void update(@RequestBody Item item){
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE,MQConstants.ITEM_INSERT_KEY,item.getId());
    }

    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        itemService.delete(id);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE,MQConstants.ITEM_DELETE_KEY,id);
    }
}
